package com.koko.controller;

import com.github.pagehelper.Page;
import com.koko.feign.AdminFeignService;
import com.koko.game.dto.*;
import com.koko.game.entity.*;
import com.koko.game.vo.*;
import com.koko.result.PageResult;
import com.koko.result.Result;
import com.koko.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/game")
public class GameController {
    @Autowired
    private GameDetailService gameDetailService;
    @Autowired
    private GameService gameService;
    @Autowired
    private PublisherService publisherService;
    @Autowired
    private GamePriceService gamePriceService;
    @Autowired
    private GameViewService gameViewService;
    @Autowired
    private GameRequireService gameRequireService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AdminFeignService adminFeignService;


    /**
     * 管理员页面分页查询
     * @param gamePageQueryDTO
     * @return
     */
    @GetMapping("/admin/page")
    @Cacheable(value = "GameCache", key = "'gamePage'")
    public PageResult<GameAdminPageItemVO> adminManagementGameList(GamePageQueryDTO gamePageQueryDTO) {
        Page<Game> gamePage = gameService.pageQuery(gamePageQueryDTO);
        List<Game> gameList = gamePage.getResult();
        List<GameAdminPageItemVO> list = gameList.stream().map((item) -> {
            GameAdminPageItemVO gameAdminPageItemVO = new GameAdminPageItemVO();
            BeanUtils.copyProperties(item, gameAdminPageItemVO);
            String simplePictureUrl = gameDetailService.getSimplePictureUrl(item.getId());
            String publisherName = publisherService.getByGameId(item.getId()).getName();
            GamePrice gamePrice = gamePriceService.getByGameId(item.getId());
            gameAdminPageItemVO.setSimplePicture(simplePictureUrl);
            gameAdminPageItemVO.setPublisher(publisherName);
            gameAdminPageItemVO.setGamePrice(gamePrice);
            return gameAdminPageItemVO;
        }).collect(Collectors.toList());
        return new PageResult<>(gamePage.getTotal(), list);
    }

    /**
     * 新增游戏
     * @param gameAddDTO
     * @return
     */
    @PostMapping("/admin")
    @CacheEvict(value = "gameCache", key = "'gamePage'")
    public Result<Long> addGame(@RequestBody GameAddDTO gameAddDTO) {
        Long gameId = gameService.save(gameAddDTO);
        return Result.success(gameId);
    }

    /**
     * 删除游戏
     * @param ids
     * @return
     */
    @DeleteMapping("/admin")
    @CacheEvict(value = "gameCache", allEntries = true)
    public Result<String> deleteGame(@RequestBody List<Long> ids) {
        gameService.deleteBatch(ids);
        return Result.success();
    }

    /**
     * 更新游戏
     * @param gameDTO
     * @return
     */
    @PutMapping("/admin")
    @CacheEvict(value = "gameCache", allEntries = true)
    public Result<String> updateGame(@RequestBody GameDTO gameDTO) {
        gameService.update(gameDTO);
        return Result.success();
    }

    /**
     * 查询游戏详细信息
     * @param id
     * @return
     */
    @GetMapping("/admin/{id}")
    @Cacheable(value = "gameCache", key = "'gameDetail' + '_' + #id")
    public Result<GameInfoVO> getGameDetailInfo(@PathVariable Long id) {
        // 查询游戏数据
        Game game = gameService.getById(id);
        GamePrice gamePrice = gamePriceService.getByGameId(id);
        GameDetail gameDetail = gameDetailService.getByGameId(id);
        GameViewListVO gameView = gameViewService.getGameViewWithIdByGameId(id);
        List<GameRequire> gameRequire = gameRequireService.getByGameId(id);
        List<CategoryVO> gameCategory = categoryService.getCategoryByGameId(id);
        GamePublisherVO gamePublisher = publisherService.getPublisherByGameId(id);
        // 通过feign查询创建人和修改人
        Result<String> createAdminResult = adminFeignService.getAdminDetail(game.getCreateUserId());
        Result<String> updateAdminResult = adminFeignService.getAdminDetail(game.getUpdateUserId());
        // 封装用户信息数据
        GameInfoVO gameInfo = GameInfoVO.builder()
                .gamePrice(gamePrice)
                .gameDetail(gameDetail)
                .gameView(gameView)
                .gameRequire(gameRequire)
                .gameCategory(gameCategory)
                .gamePublisher(gamePublisher)
                .build();
        gameInfo.setCreateUser(createAdminResult.getData());
        gameInfo.setUpdateUser(updateAdminResult.getData());
        BeanUtils.copyProperties(game, gameInfo);
        return Result.success(gameInfo);
    }

    /**
     * feign接口：获取游戏信息
     * @param id
     * @return
     */
    @GetMapping("/fromnews/{id}")
    public Result<Game> getGameInNewsById(@PathVariable Long id) {
        Game game = gameService.getById(id);
        game.setCreateTime(null);
        game.setUpdateTime(null);
        return Result.success(game);
    }

    /**
     * feign接口：获取游戏分页数据
     * @param gamePageQueryDTO
     * @return
     */
    @GetMapping("/formnews/page")
    public PageResult<Game> getGamePageInNews(GamePageQueryDTO gamePageQueryDTO) {
        Page<Game> gamePage = gameService.pageQuery(gamePageQueryDTO);
        List<Game> list = gamePage.getResult().stream().map((item) -> {
            item.setCreateTime(null);
            item.setUpdateTime(null);
            return item;
        }).collect(Collectors.toList());
        return new PageResult<>(gamePage.getTotal(), list);
    }

    /**
     * 通过发行商id获取游戏列表
     * @param publisherId
     * @return
     */
    @GetMapping("/games/bypublihserid")
    @Cacheable(value = "gameCache", key = "'gamesByPublisherId' + '_' + #publisherId")
    public Result<List<Game>> getGameByPublisherId(@RequestParam Long publisherId) {
        List<Game> list = gameService.getByPublisherId(publisherId);
        return Result.success(list);
    }

    /**
     * 获取游戏走马灯卡片信息
     * @param gameCardDTO
     * @return
     */
    @GetMapping("/carousel")
    @Cacheable(value = "gameCache", key = "'gameCarousel' + '_' + #gameCardDTO.length + '_' + #gameCardDTO.sort")
    public Result<List<GameCarouselVO>> getCarouselData(GameCardDTO gameCardDTO) {
        List<GameCarouselVO> list = gameService.getCarouselData(gameCardDTO);
        return Result.success(list);
    }

    /**
     * 获取游戏新品卡片信息
     * @param gameCardDTO
     * @return
     */
    @GetMapping("/new")
    @Cacheable(value = "gameCache", key = "'gameCard' + '_' + #gameCardDTO.length + '_' + #gameCardDTO.sort")
    public Result<List<GameNewVO>> getNewData(GameCardDTO gameCardDTO) {
        List<GameNewVO> list = gameService.getNewData(gameCardDTO);
        return Result.success(list);
    }

    /**
     * 获取游戏折扣卡片信息
     * @param gameCardDTO
     * @return
     */
    @GetMapping("/discount")
    @Cacheable(value = "gameCache", key = "'gameDiscount' + '_' + #gameCardDTO.length + '_' + #gameCardDTO.sort")
    public Result<List<GameDiscountVO>> getDiscountData(GameCardDTO gameCardDTO) {
        List<GameDiscountVO> list = gameService.getDiscountData(gameCardDTO);
        return Result.success(list);
    }

    /**
     * 获取游戏推荐卡片信息
     * @param gameCardDTO
     * @return
     */
    @GetMapping("/recommend")
    @Cacheable(value = "gameCache", key = "'gameRecommend' + '_' + #gameCardDTO.length + '_' + #gameCardDTO.sort")
    public Result<List<GameDiscountVO>> getCommendData(GameCardDTO gameCardDTO) {
        List<GameDiscountVO> list = gameService.getCommendData(gameCardDTO);
        return Result.success(list);
    }

    /**
     * 分页查询热销、最新等数据
     * @param gameListPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @Cacheable(value = "gameCache", key = "'Page' + '_' + #gameListPageQueryDTO.page + '_' + #gameListPageQueryDTO.pageSize + '_' + #gameListPageQueryDTO.type")
    public PageResult<GameDiscountVO> getPageList(GameListPageQueryDTO gameListPageQueryDTO) {
        return gameService.getListData(gameListPageQueryDTO);
    }

    /**
     * 获取游戏通用卡片信息
     * @param gameCardDTO
     * @return
     */
    @GetMapping("/common/carousel")
    @Cacheable(value = "gameCache", key = "'gameCommonCarousel' + '_' + #gameCardDTO.length + '_' + #gameCardDTO.sort + '_' + #gameCardDTO.category")
    public Result<List<GameCommonCarouselVO>> getCommonCarousel(GameCardDTO gameCardDTO) {
        List<GameCommonCarouselVO> list = gameService.getCommonCarouselData(gameCardDTO);
        return Result.success(list);
    }

    /**
     * 根据分类id查询游戏数据
     * @param gameCardDTO
     * @return
     */
    @GetMapping("/bycategory")
    @Cacheable(value = "gameCache", key = "'gameByCategory' + '_' + #gameCardDTO.length + '_' + #gameCardDTO.sort + '_' + #gameCardDTO.category")
    public Result<List<GameNewVO>> getGamesByCategoryId(GameCardDTO gameCardDTO) {
        List<GameNewVO> list = gameService.getGamesByCategoryId(gameCardDTO);
        return Result.success(list);
    }

    /**
     * 通过id获取前端游戏详细信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @Cacheable(value = "gameCache", key = "'game' + '_' + #id")
    public Result<GameFrontDetailVO> getGameFrontDetail(@PathVariable Long id) {
        GameFrontDetailVO gameFrontDetailVO = gameService.getGameFrontDetailById(id);
        return Result.success(gameFrontDetailVO);
    }

    /**
     * 购物车中的游戏信息
     * @param id
     * @return
     */
    @GetMapping("/cart/{id}")
    @Cacheable(value = "gameCache", key = "'gameOnCart' + '_' + #id")
    public Result<GameCartVO> getGameOnCartByGameId(@PathVariable Long id) {
        GameCartVO gameCartVO = gameService.getGameOnCartByGameId(id);
        return Result.success(gameCartVO);
    }
}
